package com.wujp.xml.template.core;

import freemarker.template.Configuration;
import freemarker.template.Template;
import lombok.extern.slf4j.Slf4j;

import java.io.File;
import java.io.StringWriter;
import java.io.Writer;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;

/**
 *
 */
@Slf4j
public class FreemarkerDemo {

    private static final String TEMPLATE_PATH = "templates";

    public static void main(String[] args) {
        // step1 创建freeMarker配置实例
        Configuration configuration = new Configuration(Configuration.DEFAULT_INCOMPATIBLE_IMPROVEMENTS);
        Writer out = null;
        try {
            // step2 获取模版路径
            configuration.setDirectoryForTemplateLoading(new File(ClassLoader.getSystemResource("").getPath() + File.separator + TEMPLATE_PATH));
            configuration.setEncoding(Locale.CHINA,"UTF-8");
            // step3 创建数据模型
            Map<String, Object> dataMap = new HashMap<String, Object>();
            dataMap.put("name", "张三");
            dataMap.put("age", 50);
            // step4 加载模版文件
            Template template = configuration.getTemplate("hello.ftl");
            // step5 生成数据
            // step6 输出文件
            StringWriter sw = new StringWriter();
            template.process(dataMap, sw);
            String result = sw.toString().replace("\r\n", "").replace("\r", "").trim();
            log.info(result);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
